package com.startupwebapp.services;

import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

public class PersonInfo {
	public static String getLogedInUserName() {
		Object principal = getPrincipal();
		String username = extractUserNameFromPrincipal(principal);
		return username;
	}

	private static String extractUserNameFromPrincipal(Object principal) {
		String username;
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		return username;
	}

	public static Object getPrincipal() {
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication authentication = context.getAuthentication();
		Object principal = authentication.getPrincipal();
		return principal;
	}
}
